
module.exports = (app) => {
 const assert = require("http-assert");
  const express = require("express");
  //发送token模块
  const jwt = require("jsonwebtoken");
  //引入用户登录模型
  const AdminUser = require("../../models/AdminUser");
  //http-assert能快速判断是否存在并作出响应
  const router = express.Router({
    mergeParams: true,
  });

  //创建资源
  router.post("/", async (req, res) => {
    const model = await req.Model.create(req.body);
    res.send(model);
  });
  //更新字眼
  router.put("/:id", async (req, res) => {
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body);
    res.send(model);
  });
  //删除资源
  router.delete("/:id", async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id, req.body);
    res.send({
      success: true,
    });
  });

  //登录校验中间件
 const auth =require('../../midleWare/auth')
  //资源列表
  router.get("/",auth(),async (req, res) => {
      const queryOptions = {};
      if (req.Model.modelName === "Category") {
        queryOptions.populate = "parents";
      }
      const items = await req.Model.find().setOptions(queryOptions).limit(200);
      res.send(items);
    }
  );
  //资源详情
  router.get("/:id", async (req, res) => {
    const model = await req.Model.findById(req.params.id);
    res.send(model);
  });
  app.use(
    "/admin/api/rest/:resource",
    async (req, res, next) => {
      const modelName = require("inflection").classify(req.params.resource);
      // return res.send({modelName})
      req.Model = require(`../../models/${modelName}`);
      next();
    },
    router
  );

  const multer = require("multer");
  const upload = multer({ dest: __dirname + "/../../uploads" });
  app.post("/admin/api/upload", auth(),upload.single("file"), async (req, res) => {
    const file = req.file;
    file.url = `http://localhost:3000/uploads/${file.filename}`;
    res.send(file);
  });

  // 登录路由
  app.post("/admin/api/login", async (req, res) => {
    const { username, password } = req.body;
    //根据id查找用户
    //默认不取select里的password，+password取到密码

    const user = await AdminUser.findOne({
      username: username,
    }).select("+password");
    assert(user, 422, "用户不存在");
    // if(!user){
    //     return res.status(422).send({
    //         message:"用户不存在"
    //     })
    // }
    //校验密码
    const isValid = require("bcrypt").compareSync(password, user.password);
    assert(isValid, 422, "密码错误");
    // if(!isValid){
    //     return res.status(422).send({
    //         message:'密码错误'
    //     })
    // }
    //返回token
    // const jwt =require('jsonwebtoken')
    const token = jwt.sign({ id: user._id }, app.get("secret"));
    res.send({ token });
  });
  
  //错误处理
  app.use(async(err,req,res,next)=>{
      res.status(err.statusCode ||500).send({
          message:err.message
      })
  })

};
